/*
 *  FrameListener.cpp
 *  openmove
 *
 *  Created by Sam le Pirate on 10/11/05.
 *  Copyright 2005 __MyCompanyName__. All rights reserved.
 *
 */
#include "openmove_Prefix.h"

#include "SimpleFrameListener.h"

CSimpleFrameListener :: CSimpleFrameListener(StaticGeometry *pStaticGeometry, SceneNode *pSceneNode, Entity *pEntity)
{ 
	m_pStaticGeometry = pStaticGeometry;
	m_pSceneNode = pSceneNode;
	m_pEntity = pEntity;

	Init();
} 

void CSimpleFrameListener :: Init(void)
{
	xinc = Math::PI * 0.4;
	zinc = Math::PI * 0.55;
	xpos = Math::RangeRandom(-Math::PI, Math::PI);
	zpos = Math::RangeRandom(-Math::PI, Math::PI);
}

void CSimpleFrameListener :: WaveGrass(Real timeElapsed)
{
	xpos += xinc * timeElapsed;
	zpos += zinc * timeElapsed;

	// Update vertex program parameters by binding a value to each renderable
	static Vector4 offset(0,0,0,0);

	//if (NULL != m_pStaticGeometry)
	//{
	//	StaticGeometry::RegionIterator rit =  m_pStaticGeometry->getRegionIterator();
	//	while (rit.hasMoreElements())
	//	{
	//		StaticGeometry::Region* reg = rit.getNext();

	//		// a little randomness
	//		xpos += reg->getCentre().x * 0.001 * timeElapsed;
	//		zpos += reg->getCentre().z * 0.001 * timeElapsed;
	//		offset.x = Math::Sin(xpos) * 0.05;
	//		offset.z = Math::Sin(zpos) * 0.05;

	//		StaticGeometry::Region::LODIterator lodit = reg->getLODIterator();
	//		while (lodit.hasMoreElements())
	//		{
	//			StaticGeometry::LODBucket* lod = lodit.getNext();
	//			StaticGeometry::LODBucket::MaterialIterator matit = 
	//				lod->getMaterialIterator();
	//			while (matit.hasMoreElements())
	//			{
	//				StaticGeometry::MaterialBucket* mat = matit.getNext();
	//				StaticGeometry::MaterialBucket::GeometryIterator geomit = 
	//					mat->getGeometryIterator();
	//				while (geomit.hasMoreElements())
	//				{
	//					StaticGeometry::GeometryBucket* geom = geomit.getNext();
	//					geom->setCustomParameter(999, offset);
	//				}
	//			}
	//		}
	//	}
	//}

	if (NULL != m_pSceneNode)
	{
		unsigned int const Max = m_pEntity->getNumSubEntities();
		for (unsigned int i = 0; i < Max; ++i)
		{
			// a little randomness
			xpos += m_pSceneNode->getPosition().x * Math::RangeRandom(-0.001, 0.001);
			zpos += m_pSceneNode->getPosition().z * Math::RangeRandom(-0.001, 0.001);
			offset.x = Math::Sin(xpos);
			offset.z = Math::Sin(zpos);

			m_pEntity->getSubEntity(i)->setCustomParameter(999, offset);
		}
	}
}

bool CSimpleFrameListener :: frameStarted(const FrameEvent & Evt) 
{ 
	WaveGrass(Evt.timeSinceLastFrame);
	
	return true; 
} 

// This gets called at the end of a frame. It's not necessary to use it.
bool CSimpleFrameListener :: frameEnded(const FrameEvent& Evt) 
{ 
	return true; 
} 
